package com.onluy.frameworkcloud.batis.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class   TimestampTypeHandler extends BaseTypeHandler<Object>{
	private final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";
	  private final Locale DEFAULT_LOCALE = Locale.getDefault();

	
	public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException
	  {
	    ps.setString(i, objectToString(parameter));
	  }

	  public Object getResult(ResultSet resultset, String columnName) throws SQLException
	  {
	    Object s = resultset.getObject(columnName);
	    return objectToString(s);
	  }

	  public Object getResult(CallableStatement callablestatement, int columnIndex) throws SQLException
	  {
	    Object s = callablestatement.getObject(columnIndex);
	    return objectToString(s);
	  }
	
	@Override
	public Object getNullableResult(ResultSet resultset, String columnName) throws SQLException
	  {
	    Object s = resultset.getObject(columnName);
	    return objectToString(s);
	  }

	@Override
	public Object getNullableResult(ResultSet resultset, int columnIndex) throws SQLException
	  {
	    Object s = resultset.getObject(columnIndex);
	    return objectToString(s);
	  }

	@Override
	public Object getNullableResult(CallableStatement callablestatement, int columnIndex) throws SQLException
	  {
	    Object s = callablestatement.getObject(columnIndex);
	    return objectToString(s);
	  }

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException
	{
		ps.setString(i, objectToString(parameter));
		
	}
	private String objectToString(Object obj)
	  {
		
		try {
		    if (obj == null)
		      return "";
		    if ((obj instanceof Date)) {   
		        return new SimpleDateFormat(this.DEFAULT_PATTERN, this.DEFAULT_LOCALE).format(obj);
		    }
		    else if ((obj instanceof Timestamp)) {   
		        return new SimpleDateFormat(this.DEFAULT_PATTERN, this.DEFAULT_LOCALE).format(obj);
		    }else { 
			    //return obj.getClass().getName();
		    }
		}catch(Exception e) {
			
		}
	    return obj.toString();
	  }
}
